package com.returnsoft.softphone.service;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;












import com.returnsoft.softphone.dto.PeerStateDto;
import com.returnsoft.softphone.dto.ServerDto;
import com.returnsoft.softphone.eao.PeerStateEao;
import com.returnsoft.softphone.entity.PeerState;
import com.returnsoft.softphone.entity.Server;
import com.returnsoft.softphone.exception.ConversionExcepcion;
import com.returnsoft.softphone.exception.CCenterExcepcion;
import com.returnsoft.softphone.exception.EaoExcepcion;
import com.returnsoft.softphone.util.Conversion;

/**
 * Session Bean implementation class PeerStateBean
 */
@Stateless
@LocalBean
public class PeerStateBean implements PeerStateInterface {
	
	@EJB
	private PeerStateEao peerStateEao;
	@EJB
	private Conversion conv;

    /**
     * Default constructor. 
     */
    public PeerStateBean() {
        // TODO Auto-generated constructor stub
    }
    
    @Override
	public PeerStateDto findByHost(String host, Integer ServerId) throws CCenterExcepcion {
		try {
			PeerState peerState = peerStateEao.findByHost(host,ServerId);
			return conv.fromPeerState(peerState);
		} catch (EaoExcepcion e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (ConversionExcepcion e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new CCenterExcepcion(e.getMessage());
		}
	}
    
    
    @Override
    public PeerStateDto addPeerState(PeerStateDto peerStateDto) throws CCenterExcepcion{

		try {
			
			PeerState peerStateFound = peerStateEao.find(peerStateDto.getServer().getId(), peerStateDto.getName());

				if (peerStateFound==null) {
					System.out.println("ingreso a nulo");
					PeerState peerState = conv.toPeerState(peerStateDto);
					peerState = peerStateEao.add(peerState);
					peerStateDto = conv.fromPeerState(peerState);
					return peerStateDto;	
				}else{
					
					System.out.println("NO esnulo");
					System.out.println(peerStateFound.getId());
					
					peerStateFound.setState(peerStateDto.getState());
					peerStateFound.setHost(peerStateDto.getHost());
					
					peerStateFound = peerStateEao.add(peerStateFound);
					peerStateDto = conv.fromPeerState(peerStateFound);
					return peerStateDto;	
				}
				
				
			
		} catch (EaoExcepcion e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (ConversionExcepcion e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new CCenterExcepcion(e.getMessage());
		}
		
	}
    

}
